<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Session;

Class Admin extends Model{

     public $table = 'admin';
     public $timestamps = false;

     public static function doLogin(){
         //读取验证码
         $captcha = session('vcode');
         if($_POST['code'] != $captcha){
             return json_encode(['code'=>400,'msg'=>'验证码错误']);
         }

         $username = $_POST["username"];
         $password = md5($_POST["pass"]);
         $where['adminname'] = $username;
         $admin = static :: where($where)->first();

         if (empty($admin)){
             return json_encode(['code'=>400,'msg'=>'该管理员不存在']);
         }
         if ($password != $admin->password){
             return json_encode(['code'=>400,'msg'=>'密码不正确']);
         }

         //写入本次登录时间及IP
         $admin->lastlogtime = time();
         $admin->lastlogip = get_client_ip();
         $admin->save();
         //写入SESSION
         addSession('adminid',$admin->id);
         addSession('adminname',$_POST["username"]);
         addSession('manager','y');

         if(isset($_POST['next_action']) && $_POST['next_action']!=''){
             $url = base64_decode($_POST['next_action']);
         }
         else{
             $url = 'admin/index';
         }
         echo json_encode(['code'=>200,'msg'=>'登录成功','url'=>$url]);

     }

     public static function getadminlist(){
         $data = static ::paginate(20);
         if ($data){
              $data = $data->toArray();
         }
         return $data;
     }

     public function addadminuser($req){

         if ($req['adminname'] == '' && $req['password'] == '') {
             return ['code'=>400,'msg'=>"内容不能为空"];
         }
         $res  = static :: where(['adminname'=>$req['adminname']])->first();
         if ($res) {
             return ['code'=>400,'msg'=>"该用户名已存在"];
         }
         $this->adminname = $req['adminname'];
         $this->password = md5($req['password']);
         $this->lastlogtime = 0;
         $this->lastlogip = '';
         $this->addtime = time();
         if($this->save()){
              return ['code'=>200,'msg'=>"添加成功"];
         }
         return ['code'=>400,'msg'=>"添加失败"];
     }
}